package com.wandian.weather.mvvm.weatherhome;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.dialog.ShareDialogBottom;
import com.mylib.libcore.eventbus.ChangeMessage;
import com.mylib.libcore.mvvm.BaseMVVMFragment;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.GDTADTools;
import com.mylib.libcore.tools.ShareTools;
import com.mylib.libcore.utils.ACacheUtil;
import com.mylib.libcore.utils.ImageUtil;
import com.mylib.libcore.utils.JsonUtil;
import com.mylib.libcore.utils.QRCodeUtil;
import com.mylib.libcore.utils.TimeFormate;
import com.mylib.libcore.utils.TimeUtils;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.libcore.utils.ViewUtils;
import com.wandian.weather.R;
import com.wandian.weather.adapter.WeatherFifteenDayAdapter;
import com.wandian.weather.bean.AqiBean;
import com.wandian.weather.bean.ShenshaBean;
import com.wandian.weather.bean.WeatherBean;
import com.wandian.weather.bean.WeatherInformationBean;
import com.wandian.weather.bean.YijiBean;
import com.wandian.weather.databinding.WeatherFragmentHomeBinding;
import com.wandian.weather.tools.CalendarUtil;
import com.wandian.weather.tools.LunarCalendar;
import com.wandian.weather.tools.WeatherUtil;
import com.wandian.weather.view.WeatherViewOne;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.zip.Inflater;

import me.jessyan.autosize.utils.ScreenUtils;

import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_ONE_ID;
import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_TWO_ID;
import static com.mylib.libcore.config.AppConfig.GDT_APP_MB_PIC_TWO;
import static com.mylib.libcore.config.AppSPKeyConfig.CITY_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.CITY_STREET_NAME;
import static com.mylib.libcore.config.AppSPKeyConfig.INVITE_CODE_RUL;
import static com.mylib.libcore.config.AppSPKeyConfig.PROVINCE_NAME;

/**
 * @author Administrator
 * @date 2019/12/16-13:30
 * @description 天气主页fragment
 **/
@Route(path = RouterConfig.ROUTER_FRAGMENT_WEATHER_HOME)
public class FragmentWeatherHome extends BaseMVVMFragment<FragmentWeatherHomeViewModel> implements AMapLocationListener,ShareDialogBottom.CommonDialogBtnClink{

    private WeatherFragmentHomeBinding dataBinding;
    private WeatherFifteenDayAdapter weatherFifteenDayAdapter;
    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption;
    private String latitude="";
    private String longitude="";
    private long beforeTime = System.currentTimeMillis();
    private String cityID;
    //poiSearch相关
    private PoiSearch poiSearch;
    private PoiSearch.Query query;
    boolean isPoiSearched = false; //是否进行poi搜索
    private double mCurrentLat;
    private double mCurrentLng;
    private String locationString="";
    //分享弹框
    private ShareDialogBottom shareDialogBottom;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.inflate(inflater, R.layout.weather_fragment_home, container, false);
        return dataBinding.getRoot();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        dataBinding.setViewModel(mViewModel);
        if(!UIUtils.isEmpty(dataBinding))EventBus.getDefault().register(this);
        RelativeLayout.LayoutParams linearParams =(RelativeLayout.LayoutParams) dataBinding.viewSys.getLayoutParams(); //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
        linearParams.height = ScreenUtils.getStatusBarHeight();;
        dataBinding.viewSys.setLayoutParams(linearParams);

        initRecycleFifteenDay();
        initClink();
        initViewData();
        getLocation();
        //更具时间更换背景
        TimeUtils.customHomeBgByTimeRl(getContext(),dataBinding.rlWeather);
        String  weather_json = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("weather_json");
        if(!UIUtils.isEmpty(weather_json)){
            WeatherInformationBean informationBean =(WeatherInformationBean) JsonUtil.parseJsonToBean(weather_json, WeatherInformationBean.class);
            if(!UIUtils.isEmpty(informationBean)){
                dataBinding.bindLoadView.dialogView.setVisibility(View.GONE);
                mViewModel.weatherInformationBean.setValue(informationBean);
            }
        }
        getData();

    }

    private void getData(){
         locationString =AppContext.getInstance().getAppPreferencesHelper().getLocation();
       if(!UIUtils.isEmpty(locationString)){
           String[] location = locationString.split("=");
           if(!UIUtils.isEmpty(location) && location.length>1){
               latitude = location[0]+"";
               longitude = location[1]+"";
               mViewModel.getWeatherData(location[0]+"",location[1]+"",dataBinding.bindLoadView.dialogView);
           }
       }else {
           mViewModel.getWeatherData( "29.40268", "106.54041",dataBinding.bindLoadView.dialogView);
       }
    }


    private void initClink(){
        dataBinding.srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(1500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(!UIUtils.isEmpty(dataBinding.srlRefresh))dataBinding.srlRefresh.setRefreshing(false);
                                getData();
                            }
                        });
                    }
                }).start();
            }
        });
        //天气头部
        dataBinding.layoutWeatherTop.llWeatherTop.setOnClickListener(v ->ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_REAL_WEATHER).navigation());
        //分享
        dataBinding.ivBarTitleRight.setOnClickListener(v ->{
            if(UIUtils.isFastClick())return;
            showShareDialog();
       });
        //30天天气
        dataBinding.layout15Day.tv30Day.setOnClickListener(v ->{
            if(!UIUtils.isEmpty(cityID))ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_MORE_DAY_WEATHER).withString("cityID",cityID).navigation();
        });
        //30天天气
        dataBinding.layout15Day.tvMoreDay.setOnClickListener(v ->{
            if(!UIUtils.isEmpty(cityID))ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_MORE_DAY_WEATHER).withString("cityID",cityID).navigation();
        });
        //天气地图定位
        dataBinding.llLocal.setOnClickListener(v ->   ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_MAP_WEATHER).navigation());
        //更多城市
        dataBinding.ivOtherCity.setOnClickListener(v -> ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_OTHER_CITY).navigation());
        //搜索
        dataBinding.ivBarSearch.setOnClickListener(v ->  ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_MAP_SEARCH).navigation());
        //农历
        dataBinding.llWeatherNl.setOnClickListener(v -> ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_NL).navigation());
    }


    /**
     * 获取宜忌神煞数据
     * @param
     */
    private void getYJSS(){
        //查询是否有宜忌第一条数据
        try {
            YijiBean yijiBean = DataSupport.findFirst(YijiBean.class);
            if(UIUtils.isEmpty(yijiBean)){
                mViewModel.getYJ();
            }else {
                if(UIUtils.isEmpty(ACacheUtil.getYijiData())){
                    mViewModel.getYJ();
                }
            }
        } catch (Exception e) {
            mViewModel.getYJ();
            e.printStackTrace();
        }

        //查询是否有神煞第一条数据
        try {
            ShenshaBean shenshaBean = DataSupport.findFirst(ShenshaBean.class);
            if(UIUtils.isEmpty(shenshaBean)){
                mViewModel.getSS();
            }else {
                if(UIUtils.isEmpty(ACacheUtil.getShenShaData())){
                    mViewModel.getSS();
                }
            }
        } catch (Exception e) {
            mViewModel.getSS();
            e.printStackTrace();
        }
    }

    /**
     * 15天天气recycleview
     */
    private void initRecycleFifteenDay(){
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.layout15Day.recycler15Day.setLayoutManager(layoutManager);
        weatherFifteenDayAdapter = new WeatherFifteenDayAdapter(R.layout.weather_item_style_list_15_days);
        dataBinding.layout15Day.recycler15Day.setAdapter(weatherFifteenDayAdapter);

        weatherFifteenDayAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEATHER_FIFTEEN_DAY_WEATHER).navigation();
            }
        });
    }

    private void initViewData(){

        String city_name = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(CITY_NAME);
        String city_street_name = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(CITY_STREET_NAME);
        if(!UIUtils.isEmpty(city_name)) dataBinding.tvBarTitle.setText(city_name);
        if(!UIUtils.isEmpty(city_street_name)) dataBinding.tvLocalAddress.setText(city_street_name);

        mViewModel.weatherInformationBean.observe(this,weatherInformationBean -> {
            try {
                if(!UIUtils.isEmpty(weatherInformationBean)){
                    if(!UIUtils.isEmpty( weatherInformationBean.getCity())) cityID = weatherInformationBean.getCity().getCityid();
                    AppContext.getInstance().getAppPreferencesHelper().setKeyValue("WeatherInformationBean",JsonUtil.toJson(weatherInformationBean));
                    if(!UIUtils.isEmpty(generate15dayData(weatherInformationBean))){
                        //24小时
                        try {
                            init24hourChartView(weatherInformationBean);
                        }catch (Exception e){}
                        //农历
                        initNl(weatherInformationBean);
                        //头部天气
                        if(!UIUtils.isEmpty(weatherInformationBean.getHour24()) && weatherInformationBean.getHour24().size()>0){
                            WeatherInformationBean.Hour24Bean hour24Bean = weatherInformationBean.getHour24().get(0);
                            if(!UIUtils.isEmpty(hour24Bean)){
                                dataBinding.layoutWeatherTop.ivTodayWeather.setImageResource(WeatherUtil.getWeatherStateImage(hour24Bean.getWeather()+"",false));
                                dataBinding.layoutWeatherTop.tvTemp.setText(""+hour24Bean.getStemp());
                                dataBinding.layoutWeatherTop.tvTq.setText(""+hour24Bean.getWeather());
                                dataBinding.layoutWeatherTop.tvFd.setText(""+hour24Bean.getWD()+hour24Bean.getWS());
                                dataBinding.layoutWeatherTop.tvSd.setText("湿度"+hour24Bean.getSD()+"%");
                                try {
                                    AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(hour24Bean.getAqi()));
                                    if(!UIUtils.isEmpty(aqiBean))  dataBinding.layoutWeatherTop.tvKqzl.setText("空气质量:"+aqiBean.getAqiName());
                                }catch (Exception e){

                                }
                            }

                        }
                        //15天天气
                        weatherFifteenDayAdapter.setNewData(generate15dayData(weatherInformationBean));
                    }
                    dataBinding.layoutWeatherTop.tvLater.setText(""+weatherInformationBean.getMinutely_description());
                    dataBinding.layoutWeatherTop.tvLaterZy.setText(""+ weatherInformationBean.getHourly_description());

                }
            }catch (Exception e){}
        });
        //获取yj神煞
        getYJSS();
        //获取广告
        getADShow();
    }

    private void getADShow(){
        //获取广告
        CSJADTools.loadCSJAdMiddleBanner(getContext(),dataBinding.rlAdCenter,"",CSJ_BANNER_ONE_ID,375,120);
        CSJADTools.loadCSJAdMiddleBanner(getContext(),dataBinding.rlAdBottom,"",CSJ_BANNER_TWO_ID,375,120);
        GDTADTools.loadHFAdByID(getContext(),dataBinding.adGdtLayout,GDT_APP_MB_PIC_TWO,375,0 );
    }

    /**
     * 15天天气数据
     * @return
     */
    private List<WeatherBean> generate15dayData(WeatherInformationBean weatherInformationBean) {
        List<WeatherBean> list = new ArrayList<>();
        try {
            if(!UIUtils.isEmpty(weatherInformationBean.getYesterday())){
                WeatherInformationBean.YesterdayBean yesterdayBean = weatherInformationBean.getYesterday();
                if(!UIUtils.isEmpty(yesterdayBean)){
                    WeatherBean model = new WeatherBean();
                    model.setWeek("昨天");
                    String date = TimeUtils.timeStringToTimeString(yesterdayBean.getDate(), "MM月dd日", "MM/dd");
                    model.setDate(date);
                    model.setDayTemp(Integer.parseInt(yesterdayBean.getHtemp()));
                    model.setNightTemp(Integer.parseInt(yesterdayBean.getLtemp()));
                    model.setDayWeather(yesterdayBean.getWeather());
                    model.setNightWeather(yesterdayBean.getWeather_night());
                    model.setWindOrientation(yesterdayBean.getWD());

                    AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(yesterdayBean.getAqi()));
                    model.setAqiBean(aqiBean);

                    model.setWindLevel(yesterdayBean.getWS());
//                    model.setDayPic(WeatherUtil.getWeatherStateImage(yesterdayBean.getImg_num(), 48));
//                    model.setNightPic(WeatherUtil.getWeatherStateImage(yesterdayBean.getImg_num(), true,48));
                    list.add(model);
                }
            }
            for (int i = 0; i < weatherInformationBean.getWeather30().size(); i++) {
                if(i<15){
                    Log.d("generate15dayData", "111111");
                    WeatherInformationBean.Weather30Bean weather30Bean = weatherInformationBean.getWeather30().get(i);
                    WeatherBean model = new WeatherBean();
                    if (i == 0) {
                        model.setWeek("今天");
                    } else if (i == 1) {
                        model.setWeek("明天");
                    } else {
                        model.setWeek(weather30Bean.getWeek().replace("星期", "周"));
                    }
                    String date = TimeUtils.timeStringToTimeString(weather30Bean.getDate(), "MM月dd日", "MM/dd");
                    model.setDate(date);
                    model.setDayTemp(Integer.parseInt(weather30Bean.getHtemp()));
                    model.setNightTemp(Integer.parseInt(weather30Bean.getLtemp()));

                    if(!UIUtils.isEmpty(weather30Bean.getWeather_day())){
                        model.setDayWeather(weather30Bean.getWeather_day());
                    }else {
                        model.setDayWeather(weather30Bean.getWeather());
                    }
                    model.setNightWeather(weather30Bean.getWeather_night());
                    model.setWindOrientation(weather30Bean.getWD());

                    AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(weather30Bean.getAqi()));
                    model.setAqiBean(aqiBean);
                    list.add(model);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 农历
     * @return
     */
    private void initNl(WeatherInformationBean weatherInformationBean) {
        try {
            if (weatherInformationBean != null) {
                WeatherInformationBean.NlBean nlBean = weatherInformationBean.getNl();
                String date = TimeFormate.timeStringToTimeString(nlBean.getDate(), "yyyyMMdd", "MM月dd日");
                String week = nlBean.getMore().getWeek();
                dataBinding.itemNlTitle.tvNlDateWeek.setText(week);
                dataBinding.itemNlTitle.tvNlDate.setText(date);

                TextView[] tvJis = new TextView[]{dataBinding.itemNl.tvJi1, dataBinding.itemNl.tvJi2, dataBinding.itemNl.tvJi3, dataBinding.itemNl.tvJi4, dataBinding.itemNl.tvJi5, dataBinding.itemNl.tvJi6};
                TextView[] tvYis = new TextView[]{dataBinding.itemNl.tvYi1, dataBinding.itemNl.tvYi2, dataBinding.itemNl.tvYi3, dataBinding.itemNl.tvYi4, dataBinding.itemNl.tvYi5, dataBinding.itemNl.tvYi6};

                String[] strYis = nlBean.getMore().getY().split(" ");
                String[] strJis = nlBean.getMore().getJ().split(" ");

                int tagJi = strJis.length >= 6 ? 6 : strJis.length;
                for (int i = 0; i < tagJi; i++) {
                    tvJis[i].setVisibility(View.VISIBLE);
                    tvJis[i].setText(strJis[i]);
                }

                int tagYi = strYis.length >= 6 ? 6 : strYis.length;
                for (int i = 0; i < tagYi; i++) {
                    tvYis[i].setVisibility(View.VISIBLE);
                    tvYis[i].setText(strYis[i]);
                }

                Calendar calDay = Calendar.getInstance();
                dataBinding.itemNlTitle.tvOldLunar.setText(nlBean.getBase().getMonth_text()+nlBean.getBase().getDay_text());

                LunarCalendar lunarCalendar = new LunarCalendar();
                CalendarUtil util = new CalendarUtil(calDay);
                HashMap<String, Object> map = lunarCalendar.getBaseInfo(calDay.get(Calendar.YEAR), (calDay.get(Calendar.MONTH) + 1), calDay.get(Calendar.DATE));
                String jsonString = JsonUtil.toJson(map);
                JSONObject jsonObject =new JSONObject(jsonString);

                String oldMonth = jsonObject.getJSONObject("oldtime").getString("month");
                String oldDay = jsonObject.getJSONObject("oldtime").getString("day");
                int week1 = calDay.get(Calendar.WEEK_OF_YEAR);
                String weekNum = "第" + week1 + "周";
                String descOldLunar = weekNum + "  " + util.cyclical() + "[" + util.animalsYear() + "]年 " + oldMonth + "月  "
                        + oldDay + "日";
                dataBinding.itemNlTitle.tvDescOldLunar.setText(descOldLunar);

                dataBinding.itemNlTitle.tvJiejiari.setText(weatherInformationBean.getWeather30().get(0).getNl().getJr());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 24小时天气折线图
     * @return
     */
    private void init24hourChartView(WeatherInformationBean weatherInformationBean) {

        //画曲线(已修复不圆滑问题)
        dataBinding.layout24Hour.weatherViewOne.setLineType(WeatherViewOne.LINE_TYPE_DISCOUNT);

        //设置线宽
        dataBinding.layout24Hour.weatherViewOne.setLineWidth(2f);

        //设置白天和晚上线条的颜色
        dataBinding.layout24Hour.weatherViewOne.setDayLineColor(Color.parseColor("#2FDC94"));

        //填充天气数据
        dataBinding.layout24Hour.weatherViewOne.setList(generateHourData(weatherInformationBean),false);
        if (Build.VERSION.SDK_INT >= 22){
            dataBinding.layout24Hour.weatherViewOne.setNestedScrollingEnabled(false);
        }
        dataBinding.layout24Hour.weatherViewOne.post(new Runnable() {
            @Override
            public void run() {
                dataBinding.layout24Hour.weatherViewOne.invalidate();
            }
        });

    }

    /**
     * 24小时天气数据
     * @return
     */
    private List<WeatherBean> generateHourData( WeatherInformationBean weatherInformationBean) {
        List<WeatherBean> list = new ArrayList<>();
        try {
            for (WeatherInformationBean.Hour24Bean hour24Bean : weatherInformationBean.getHour24()) {
                WeatherBean model = new WeatherBean();
                model.setDate(hour24Bean.getDatetime());
                model.setDayWeather(hour24Bean.getWeather() + "");
                model.setWeek(hour24Bean.getHour());
                model.setDayTemp(Integer.parseInt(hour24Bean.getStemp()));

                AqiBean aqiBean = WeatherUtil.getAqiBean(getContext(), Integer.parseInt(hour24Bean.getAqi()));
                model.setNightWeather(aqiBean.getAqiName());
                model.setWindLevel(hour24Bean.getWS());
                model.setAqiBean(aqiBean);
//                model.setDayPic(WeatherUtil.getWeatherStateImage(hour24Bean.getImg_num(), 48));
//                model.setNightPic(WeatherUtil.getWeatherStateImage(hour24Bean.getImg_num(), true,48));
                model.setWindOrientation(hour24Bean.getWD());
                list.add(model);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }


    //获取当前坐标
    private void getLocation(){
        mlocationClient = new AMapLocationClient(getContext());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        if(!UIUtils.isEmpty(mlocationClient) && !UIUtils.isEmpty(mLocationOption)){
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption.setInterval(30*60*1000);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            //启动定位
            mlocationClient.startLocation();
        }
    }


    /**
     * 搜索poi
     * @param key      关键字
     * @param pageNum  页码
     * @param cityCode 城市代码，或者城市名称
     * @param nearby   是否搜索周边
     */
    void searchPoi(String key, int pageNum, String cityCode, boolean nearby) {
        isPoiSearched = true;
        query = new PoiSearch.Query(key, "", cityCode);
        //keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，
        //POI搜索类型共分为以下20种：汽车服务|汽车销售|
        //汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|
        //住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|
        //金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施
        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(30);// 设置每页最多返回多少条poiitem
        query.setPageNum(pageNum);//设置查询页码
        poiSearch = new PoiSearch(getContext(), query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                //填充数据，并更新
                if (poiResult != null) {
                    ArrayList<PoiItem> result = poiResult.getPois();
                    if (result.size() > 0) {
                        if(!UIUtils.isEmpty(result.get(0))){
                            AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_NAME,result.get(0).getCityName());
                            AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_STREET_NAME,result.get(0).getTitle());
                            dataBinding.tvBarTitle.setText(result.get(0).getCityName()+"");
                            dataBinding.tvLocalAddress.setText(result.get(0).getAdName()+result.get(0).getTitle()+"");
                            mViewModel.getWeatherData(result.get(0).getLatLonPoint().getLatitude()+"",
                                    result.get(0).getLatLonPoint().getLongitude()+""
                                    ,dataBinding.bindLoadView.dialogView);
                        }
                    }
                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        if (nearby) poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mCurrentLat, mCurrentLng), 1500));//设置周边搜索的中心点以及半径
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                //重庆市渝中区民生路235号靠近重庆JW万豪酒店=海航保利国际中心=重庆市=渝中区=重庆市=民生路
                dataBinding.tvBarTitle.setText(amapLocation.getCity()+"");
                dataBinding.tvLocalAddress.setText(amapLocation.getDistrict()+ amapLocation.getStreet()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(PROVINCE_NAME,amapLocation.getProvince()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_NAME,amapLocation.getCity()+"");
                AppContext.getInstance().getAppPreferencesHelper().setKeyValue(CITY_STREET_NAME,amapLocation.getDistrict()+ amapLocation.getStreet()+"");
               // Log.d("amapLocation=", amapLocation.getAddress()+"="+amapLocation.getAoiName()+"="+amapLocation.getCity()+"="+amapLocation.getDistrict()+"="+amapLocation.getProvince()+"="+amapLocation.getStreet());
//                if(!UIUtils.isEmpty(mViewModel)){
//                    mViewModel.submitLocalData(amapLocation.getLongitude()+"",amapLocation.getLatitude()+"",amapLocation.getProvince()+"",amapLocation.getCity()+"",amapLocation.getStreet()+"",amapLocation.getAddress()+"");
//                }
                if(latitude.equals(amapLocation.getLatitude()+"") && longitude.equals(amapLocation.getLongitude()+"")){
                }else {
                    AppContext.getInstance().getAppPreferencesHelper().setLocation(amapLocation.getLatitude()+"",amapLocation.getLongitude()+"");
                    mViewModel.getWeatherData(amapLocation.getLatitude()+"",
                            amapLocation.getLongitude()+"",dataBinding.bindLoadView.dialogView);
                }
                if(UIUtils.isEmpty(locationString)){
                    latitude = amapLocation.getLatitude()+"";
                    longitude = amapLocation.getLongitude()+"";
                    mViewModel.getWeatherData(latitude,longitude,dataBinding.bindLoadView.dialogView);
                    //设置经纬度
                    AppContext.getInstance().getAppPreferencesHelper().setLocation(amapLocation.getLatitude()+"",amapLocation.getLongitude()+"");
                }

            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError","location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

   @Subscribe(threadMode = ThreadMode.MAIN)
   public void eventBusMessage(ChangeMessage changeMessage) {
       try {
           if(!UIUtils.isEmpty(changeMessage) && !UIUtils.isEmpty(changeMessage.getIsChange())){
               //城市定位
               if(changeMessage.getIsChange().equals("changeWeatherCity")){
                   Log.d("changeWeatherCity","changeWeatherCity" );
                   String searchAddress = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("select_address");
                   if(!UIUtils.isEmpty(searchAddress)){
                       searchPoi(searchAddress, 0, null, false);
                   }else {
                       String searchCity = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("select_city");
                       if(!UIUtils.isEmpty(searchCity)){
                           searchPoi(searchCity, 0, null, false);
                       }
                   }
               }
               //坐标定位
               if(changeMessage.getIsChange().equals("changeWeatherLocal")){
                   Log.d("changeWeatherLocal","changeWeatherLocal" );
                   String city_name = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(CITY_NAME);
                   String city_street_name = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(CITY_STREET_NAME);
                   if(!UIUtils.isEmpty(city_name)) dataBinding.tvBarTitle.setText(city_name);
                   if(!UIUtils.isEmpty(city_street_name)) dataBinding.tvLocalAddress.setText(city_street_name);
                   String select_lat = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("select_lat");
                   String select_log = AppContext.getInstance().getAppPreferencesHelper().getKeyValue("select_log");
                   mViewModel.getWeatherData(select_lat,select_log,dataBinding.bindLoadView.dialogView);
               }
               if(changeMessage.getIsChange().equals("changeWeather")){
                   Log.d("changeWeather","changeWeather" );
                   //获取广告
                   getADShow();
                   if(System.currentTimeMillis()-beforeTime>3*60*1000){
                       beforeTime = System.currentTimeMillis();
                       getData();
                   }
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

    //展示分享弹框
    private void showShareDialog(){
        try {
            shareDialogBottom = new ShareDialogBottom(getContext(),this::btnClink);
            //显示窗口
            //设置layout在PopupWindow中显示的位置
            if(!UIUtils.isEmpty(dataBinding.rlWeather)){
                shareDialogBottom.showAtLocation(dataBinding.rlWeather, Gravity.BOTTOM, 0, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        try {
            EventBus.getDefault().unregister(this);
            if(!UIUtils.isEmpty(mlocationClient))  mlocationClient.onDestroy();
        }catch (Exception e){}
        super.onDestroy();
    }

    @Override
    public void btnClink(String text, String type, String id) {
        String invite_url = AppContext.getInstance().getAppPreferencesHelper().getKeyValue(INVITE_CODE_RUL)+"";
        if(!UIUtils.isEmpty(invite_url)){
            // Bitmap logoBitmap= BitmapFactory.decodeResource(getResources(),R.drawable.app_logo);
            final Bitmap er_bitmap = QRCodeUtil.createQRImage(invite_url, 110, 110, null, null);
            if(!UIUtils.isEmpty(er_bitmap)){
                dataBinding.ivErCode.setImageBitmap(er_bitmap);
            }
        }
        Bitmap share_bitmap = ViewUtils.toBitmap(dataBinding.rlWeather);
        if(!UIUtils.isEmpty(share_bitmap)){
            dataBinding.ivErCode.setImageResource(R.color.transparent);
            switch (type){
                case "微信":
                    ShareTools.shareWxPic(getContext(),share_bitmap,0);// 0：分享到好友  1：分享到朋友圈
                    break;
                case "朋友圈":
                    ShareTools.shareWxPic(getContext(),share_bitmap,1);// 0：分享到好友  1：分享到朋友圈
                    break;
                case "QQ":
                    ToastUtil.show("分享QQ");
                    break;
                case "复制":
                    ToastUtil.show("已复制");
                    break;
            }

        }
    }
}
